package main

import (
	"flag"
	"html/template"
	"log"
	"net/http"

	"github.com/gorilla/websocket"
)

type Echo struct {
	addr     *string
	wsUpgrde websocket.Upgrader
}

func (echo Echo) init() {
	echo.addr = flag.String("addr", "localhost:8080", "http server address")
	echo.wsUpgrde = websocket.Upgrader{}
	log.Println("echo init ok")
}

func (echo Echo) startServe() {
	flag.Parse()
	log.SetFlags(0)
	// log.Println(*echo.addr)
	http.HandleFunc("/echo", echo.echo)
	http.HandleFunc("/", echo.home)
	log.Println("echo start serve")
	log.Fatal(http.ListenAndServe("localhost:8080", nil))
}

func (echo Echo) echo(w http.ResponseWriter, r *http.Request) {
	c, err := echo.wsUpgrde.Upgrade(w, r, nil)
	if err != nil {
		log.Print("upgrade:", err)
		return
	}
	defer c.Close()
	for {
		mt, message, err := c.ReadMessage()
		if err != nil {
			log.Println("read:", err)
			break
		}
		log.Printf("recv: %s", message)
		err = c.WriteMessage(mt, message)
		if err != nil {
			log.Println("write:", err)
			break
		}
	}
}

func (echo Echo) home(w http.ResponseWriter, r *http.Request) {
	var homeTemplate = template.Must(template.ParseFiles("index.html"))

	homeTemplate.Execute(w, "ws://"+r.Host+"/echo")
}
